package com.pl.code.desktop.controller;

import com.pl.code.desktop.core.DataSourceHelper;
import com.pl.code.desktop.entity.po.datasource.PlDataSource;
import com.pl.code.desktop.service.datasource.IDataSourceService;
import com.pl.core.utils.AssertUtil;
import com.pl.data.core.response.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;

/**
 * @ClasssName ServerController
 * @Description 连接服务相关API
 * @Author Liuyh
 * @Date 2021/9/17
 * @Version V0.0.1
 */
@RestController
@RequestMapping("server")
@Api(tags = "数据源连接")
public class ServerController {
    @Autowired
    private IDataSourceService dataSourceService;


    /**
     * 连接
     *
     * @param id
     * @return
     */
    @GetMapping("connection/{id}")
    @ApiOperation("连接数据源")
    public Result<Boolean> connection(@ApiParam("数据源id") @Validated @NotNull(message = "数据源不能为空") Long id) {
        PlDataSource dataSource = dataSourceService.getById(id);
        AssertUtil.notNull(dataSource, "未查询到连接信息");
        boolean connectionState = DataSourceHelper.add(dataSource);
        AssertUtil.isTrue(connectionState, "连接失败");
        return Result.ok(connectionState);
    }


    /**
     * 关闭连接
     *
     * @param id
     * @return
     */
    @GetMapping("close/{id}")
    @ApiOperation("关闭数据源连接")
    public Result<Boolean> close(@ApiParam("数据源id") @Validated @NotNull(message = "数据源不能为空") Long id) {
        PlDataSource dataSource = dataSourceService.getById(id);
        AssertUtil.notNull(dataSource, "未查询到连接信息");
        boolean connectionState = DataSourceHelper.close(dataSource.getName());
        AssertUtil.isTrue(connectionState, "关闭失败");
        return Result.ok(connectionState);
    }


}
